"""
    Author:
    Date: 2019-04-04

    APP管理类
"""

from entities import user_mgr
from entities.consts import *
from utils import db


def get_app_channels_basic_info(begin_time, end_time, app):
    """ 获取指定app渠道的基本信息 """
    def create_channel_info(channel_code):
        info = get_channel_info(channel_code)
        channel_list[channel_code] = {
            'code': info['code'],
            'name': info['name'],
            'icon': info['icon'],
            'new_user_count': 0,
            'pay_amount': 0,
        }
        return info

    channel_list = {}
    # 每日新增
    records = user_mgr.get_new_users_by_channel(begin_time, end_time, app)
    for record in records:
        channel = record['channel']
        value = record['value']

        if channel not in channel_list:
            channel_info = create_channel_info(channel)
        channel_list[channel]['new_user_count'] = value

    # 每日充值
    records = user_mgr.get_pay_data_by_channel(begin_time, end_time, app)
    for record in records:
        channel = record['channel']
        value = record['value']

        if channel not in channel_list:
            channel_info = create_channel_info(channel)
        channel_list[channel]['pay_amount'] = value

    # 按充值金额排序
    data = [v for k, v in channel_list.items()]
    data.sort(key=lambda x: x['pay_amount'], reverse=True)

    return data


def get_app_list():
    """ 获取应用列表 """
    sql = f'''
        SELECT      *
        FROM        cmf_config_app
        ORDER BY    sterilize_type DESC, id DESC;
    '''
    data = db.query_data_from_db(sql)
    return data if data else []


def get_channel_list():
    """ 获取配置的渠道列表 """
    sql = f'''
        SELECT      *
        FROM        cmf_app_channels
        ORDER BY    sterilize_type DESC;
    '''
    data = db.query_data_from_db(sql)
    return data if data else []


def get_all_channel_list():
    """ 获取所有的渠道列表 """
    sql = f'''
        SELECT      channel, COUNT(*) AS user_count
        FROM        cmf_users
        GROUP BY    channel
        ORDER BY    channel;
    '''
    data = db.query_data_from_db(sql)
    return data if data else []


def update_app_sterilize_type(app_id, sterilize_type):
    """ 更新APP的过滤类型 """
    sql = f'''
        UPDATE      cmf_config_app
        SET         sterilize_type={sterilize_type}
        WHERE       id={app_id}
        LIMIT       1;
    '''
    affected_rows = db.execute_sql(sql)
    return affected_rows == 1


def update_channel_sterilize_type(channel_id, sterilize_type):
    """ 更新APP的过滤类型 """
    sql = f'''
        UPDATE      cmf_app_channels
        SET         sterilize_type={sterilize_type}
        WHERE       id={channel_id}
        LIMIT       1;
    '''
    affected_rows = db.execute_sql(sql)
    return affected_rows == 1


if __name__ == '__main__':
    print('ok')
